package com.zhuiyun.educations.api.User.service.impl;
import com.zhuiyun.educations.api.User.entity.User;
import com.zhuiyun.educations.api.User.mapper.UserMapper;
import com.zhuiyun.educations.api.User.service.UserService;
import com.zhuiyun.educations.api.rotationimage.entity.ImageFile;
import com.zhuiyun.educations.api.rotationimage.mapper.ImageFileMapper;
import com.zhuiyun.educations.common.response.CommonResult;
import com.zhuiyun.educations.util.ObjectUtils;
import com.zhuiyun.educations.util.RedisUtil;
import com.zhuiyun.educations.util.UploadFileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;

/**
 * @ClassName UserSerivce
 * @Description TODO
 * @Author 12295
 * @Date 2023/6/15 10:06
 **/
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Resource
    JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String from;
    @Resource
    UploadFileUtils uploadFileUtils;
    @Resource
    ImageFileMapper imageFileMapper;

    /**
    * @Author yangze
    * @Description Todo 账号密码登录
    * @Date 2023/6/15 16:08
    * @Return
    * @param loginName
    */

    @Override
    public User getUserByLoginName(String loginName) {
        if(ObjectUtils.isNotEmpty(loginName)){
            // 使用Example表达式查询登录人信息
            Example example = new Example(User.class);
            example.createCriteria().andEqualTo("userName",loginName);
            return userMapper.selectOneByExample(example);
        }else{
            return null;
        }
    }

    @Override
    public Object sendEmail(String email) {
        Random random = new Random();
        String sjs = String.valueOf(random.nextInt(999999));
        try{
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);//发送人
            message.setSubject("【邮箱验证】");
            message.setText("非凡教育,您的验证码是: "+sjs+"请在五分钟内完成验证");
            message.setTo(email);//接收人
            javaMailSender.send(message);
    }catch (Exception e) {
        e.printStackTrace();
        return "发送失败";
    }

        RedisUtil.set(email,sjs,300);
        return "发送成功";
    }


    /**
    * @Author yangze
    * @Description  TODO 校验名字是否存在
    * @Date 2023/6/19 19:55
    * @Return
    * @param userName
    */

    @Override
    public Object getUserByUserName(String userName) {
        if(ObjectUtils.isNotEmpty(userName)){
            // 使用Example表达式查询登录人信息
            Example example = new Example(User.class);
            example.createCriteria().andEqualTo("userName",userName);
            return userMapper.selectOneByExample(example);

    }
        return null;
    }

    @Override
    public Object getUserByEmail(String email) {

        if(ObjectUtils.isNotEmpty(email)){
            // 使用Example表达式查询登录人信息
            Example example = new Example(User.class);
            example.createCriteria().andEqualTo("email",email);
            return userMapper.selectOneByExample(example);

        }
        return null;
    }

    @Override
    public Object register(User user, String code) {
        if (ObjectUtils.isNotEmpty(user)) {
            if (ObjectUtils.isNotEmpty(code)) {
                String redisCode = (String) RedisUtil.get(user.getEmail());
                if (redisCode.equals(code)) {
                    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
                    Date date = new Date();
                    user.setCreateTime(date);
                    user.setUpdateTime(date);
                    user.setAvatarUrl("1241");
                    userMapper.insert(user);
                    return "注册成功";
                } else {
                    return "验证码错误";
                }
            } else {
                return "验证码不能为空";
            }
        }
        return "注册失败";
    }

    /**
     * @Author cjl
     * @Description 根据用户id查询信息(除了密码)
     * @Date 2023/6/20 19:37
     * @Return com.zhuiyun.educations.common.response.CommonResult
     * @param id
     */
    @Override
    public CommonResult selectUserbyId(Integer id) {
        User user = userMapper.selectUserbyId(id);
        return CommonResult.ok(user);
    }
    /**
     * @Author cjl
     * @Description  根据id修改用户信息(除了密码)
     * @Date 2023/6/21 17:57
     * @Return com.zhuiyun.educations.common.response.CommonResult
     * @param user
     */
    @Override
    public CommonResult updateUserByLoginNameById(User user) {
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i!=0){
            return CommonResult.ok("恭喜你，修改成功！");
        }else {
            return CommonResult.error(1000,"修改用户名失败!!!");
        }
    }
    /**
    * @Author cjl
    * @Description 根据电话查询是否绑定了手机号
    * @Date 2023/6/23 9:03
    * @Return com.zhuiyun.educations.common.response.CommonResult
    * @param phone
    */
    @Override
    public CommonResult selectUserByPhone(String phone) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("phone",phone);
        User user = userMapper.selectOneByExample(example);
        return CommonResult.ok(user);
    }
    /**
     * @Author cjl
     * @Description 根据邮箱查询是否重复的邮箱
     * @Date 2023/6/23 14:11
     * @Return com.zhuiyun.educations.common.response.CommonResult
     * @param email
     */
    @Override
    public CommonResult selectUserByEmail(String email) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("email",email);
        User user = userMapper.selectOneByExample(example);
        return CommonResult.ok(user);
    }
    /**
     * @Author cjl
     * @Description 根据登录名查询是否重复的名称
     * @Date 2023/6/23 14:11
     * @Return com.zhuiyun.educations.common.response.CommonResult
     * @param loginName
     */
    @Override
    public CommonResult selectUserByLoginName(String loginName) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("loginName",loginName);
        User user = userMapper.selectOneByExample(example);
        return CommonResult.ok(user);
    }

    @Override
    public CommonResult sendVerificationCode(String phone) {
        // 生成验证码
        String newCode = "";
        //随机生成验证码
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            newCode += random.nextInt(10);
        }
        RedisUtil.set(phone,newCode,500);
        return CommonResult.ok(newCode);
    }

    @Override
    public CommonResult verifyPhone(String phone, String verificationCode) {
        Object code = RedisUtil.get(phone);
        if (code.equals(verificationCode)){
            return CommonResult.ok("验证成功");
        }else {
            return CommonResult.error(1000,"验证失败");
        }
    }

    public CommonResult findPassword(String email, String code, String password) {
        if (ObjectUtils.isNotEmpty(email)) {
            if (ObjectUtils.isNotEmpty(code)) {
                String redisCode = (String) RedisUtil.get(email);
                if (redisCode.equals(code)) {
                    Example example = new Example(User.class);
                    example.createCriteria().andEqualTo("email",email);
                    User user = userMapper.selectOneByExample(example);
                    user.setPassword(bCryptPasswordEncoder.encode(password));
                    userMapper.updateByPrimaryKeySelective(user);
                    return CommonResult.ok("修改成功");
                } else {
                    return CommonResult.error(1000,"验证码错误");
                }
            } else {
                return CommonResult.error(1000,"验证码不能为空");
            }
        }
        return CommonResult.ok();
    }

    @Override
    @Transactional
    public CommonResult updateUserById(MultipartFile imageFile, User user) {
        if(user.getId()!=null&&user.getId()!=0){
            if(imageFile!=null){
                //获取图片唯一id
                String s=uploadFileUtils.uploadFile(imageFile);
                //判断id是否为空
                if(!StringUtils.isEmpty(s)) {
                    //将图片信息存入数据库
                    ImageFile image=new ImageFile();
                    String originalFilename = imageFile.getOriginalFilename();
                    System.out.println("originalFilename：：：：：：："+originalFilename);
                    String fileExtension = "";
                    int dotIndex = originalFilename.lastIndexOf(".");
                    if (dotIndex > 0 && dotIndex < originalFilename.length() - 1) {
                        fileExtension = originalFilename.substring(dotIndex + 1);
                    }
                    System.out.println("type：：：：：：："+fileExtension);
                    image.setImageName(s);
                    System.out.println("ImageName：：：：：：："+image.getImageName());
                    image.setCreateTime(new Date());
                    System.out.println("CreateTime：：：：：：："+new Date());
                    image.setUpdateTime(new Date());
                    System.out.println("UpdateTime：：：：：：："+new Date());
                    image.setFileSize(imageFile.getSize());
                    System.out.println("FileSize：：：：：：："+imageFile.getSize());
                    image.setFileUuidName(originalFilename);
                    System.out.println("FileUuidName：：：：：：："+originalFilename);
                    image.setFileType(fileExtension);
                    System.out.println("FileType：：：：：：："+fileExtension);
                    //持久化操作
                    imageFileMapper.insertSelective(image);
                    //将图片id赋值给user
                    user.setAvatarUrl(s);
                    int i = userMapper.updateByPrimaryKeySelective(user);
                    if(i>0){
                        return CommonResult.ok("添加成功");
                    }
                    return CommonResult.error(500,"添加失败");
                }
                return CommonResult.error(500,"图片上传失败");
            }
            int i = userMapper.updateByPrimaryKeySelective(user);
            if(i>0){
                return CommonResult.ok("添加成功");
            }
            return CommonResult.error(500,"添加失败");
        }
        return CommonResult.error(500,"id为null");
    }
}
